package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    private static final Logger log = LoggerFactory.getLogger(AddressBookServiceImpl.class);
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     *
     * @param addressBook
     * @return void
     */
    @Override
    public void addAddress(AddressBook addressBook) {
        Long currentId = BaseContext.getCurrentId();
        addressBook.setUserId(currentId);
        addressBook.setIsDefault(0);
        addressBookMapper.addAddress(addressBook);
    }

    /**
     * 查询全部地址
     *
     * @param
     * @return void
     */
    @Override
    public List<AddressBook> list(AddressBook addressBook) {
        return addressBookMapper.list(addressBook);
    }

    /**
     * 查询默认地址
     *
     * @param addressBook
     * @return List<AddressBook>
     */
    @Override
    public List<AddressBook> defaultAddress(AddressBook addressBook) {
        AddressBook build = AddressBook.builder()
                .isDefault(1)
                .build();
        List<AddressBook> list = addressBookMapper.list(build);
        return list;
    }


    /**
     * 根据id修改地址
     *
     * @param addressBook
     */
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id查询地址
     *
     * @param id
     * @return List<AddressBook>
     */
    @Override
    public List<AddressBook> selectById(Long id) {
        List<AddressBook> list = addressBookMapper.selectById(id);
        return list;
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     */
    @Transactional
    public void setDefaultAddress(AddressBook addressBook) {
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsDefaultByUserId(addressBook);

        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }

    /**
    * 根据id删除
    * @param id
    * @return void
    */
    @Override
    public void deleteById(Integer id) {
        addressBookMapper.deleteById(id);
    }
}
